package com.cunjiankang.ui;

import android.app.Dialog;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.cunjiankang.R;
import com.cunjiankang.adapter.GuidePageAdapter;
import com.cunjiankang.bean.request.HealthInfoRequest;
import com.cunjiankang.bean.response.BaseResponse;
import com.cunjiankang.bean.vo.HealthChartBean;
import com.cunjiankang.bean.vo.HealthChartListBean;
import com.cunjiankang.util.*;
import com.cunjiankang.view.CustomProgressDialog;
import com.cunjiankang.view.DoubleDatePickerDialog;
import com.cunjiankang.view.DoubleDatePickerDialog.OnDateSetListener;
import com.cunjiankang.view.SelectDialog;
import com.cunjiankang.view.SelectDialog.DialogInterfaceListener;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.SystemTool;

import java.util.Calendar;

/**
 * 
 * @ClassName: HealthChartActivity
 * @Description:
 * @author liyongqiang
 * @date 2015-3-5 下午11:39:23
 * 
 */
public class HealthChartActivity extends BaseActivity implements
		OnPageChangeListener {

	@BindView(id = R.id.viewpager)
	private ViewPager mViewPager;
	@BindView(id = R.id.viewGroup)
	private ViewGroup mViewGroup;
	@BindView(id = R.id.layout_root)
	private LinearLayout mLinearLayout;
	/*
	 * @BindView(id=R.id.title) private TextView mTitleTextView;
	 */
	@BindView(id = R.id.value_change_1)
	private TextView mValue1TextView;
	@BindView(id = R.id.value_change_2)
	private TextView mValue2TextView;
	@BindView(id = R.id.value_change_3)
	private TextView mValue3TextView;
	@BindView(id = R.id.btn_1, click = true)
	private Button mButton1;
	@BindView(id = R.id.btn_2, click = true)
	private Button mButton2;
	@BindView(id = R.id.btn_3, click = true)
	private Button mButton3;
	@BindView(id = R.id.btn_linear)
	private LinearLayout mBtnLinear;
	@BindView(id = R.id.btn_select, click = true)
	private Button btnSelect;
	/*
	 * @BindView(id=R.id.tv_date) private TextView tvDate;
	 */
	@BindView(id = R.id.btn_back, click = true)
	private Button btnBack;
	@BindView(id = R.id.tv_info)
	private TextView tvInfo;

	private GuidePageAdapter mGuidePageAdapter;
	private HealthChartListBean mHealthChartListBean;
	private ImageView[] mImageViews;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_chart);
		super.setRootView();
	}

	public static boolean lastTime = false;

	private void queryData(String timetype, String begintime, String endtime) {
		HealthInfoRequest healthInfoRequest = new HealthInfoRequest();
		healthInfoRequest.type = Contants.ApiKey.graphdetail;
		healthInfoRequest.loginid = PreferenceUtil.readString(this,
				Contants.SP.login_id);
		healthInfoRequest.begintime = begintime;
		healthInfoRequest.endtime = endtime;
		healthInfoRequest.timetype = timetype;
		healthInfoRequest.key = getIntent().getStringExtra("key");
		final Dialog dialog = CustomProgressDialog.createDialog(this)
				.setMessage(R.string.loading);
		dialog.show();
		HttpUtil.post(healthInfoRequest, new HttpCallBack() {
			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				KJLoger.debug(t);
				mHealthChartListBean = ParseResponseUtil.parseHealthData(t);
				if (mHealthChartListBean.result
						.equals(BaseResponse.flag_success)) {

					mGuidePageAdapter
							.setData(mHealthChartListBean.healthChartBeans);
					mGuidePageAdapter
							.setCount(mHealthChartListBean.healthChartBeans
									.size());
					mImageViews = new ImageView[mHealthChartListBean.healthChartBeans
							.size()];
					if (mHealthChartListBean.healthChartBeans.size() > 0) {
						/*
						 * mTitleTextView
						 * .setText(mHealthChartListBean.healthChartBeans
						 * .get(0).title);
						 * 
						 * if (mTitleTextView.getText().equals("餐前")) {
						 * mBtnLinear.setVisibility(View.VISIBLE); }
						 */
					}

					String recentStr[] = new String[3];
					HealthChartBean healthChartBean = mHealthChartListBean.healthChartBeans
							.get(0);
					String recentTitleStr[] = healthChartBean.recentTitle;
					String recentValue[][] = healthChartBean.recentValue;
					SpannableStringBuilder sp[] = new SpannableStringBuilder[3];
					for (int m = 0; m < recentTitleStr.length; m++) {
						if (m < 3) {
							recentStr[m] = new StringBuffer(recentTitleStr[m])
									.append(" ").append(recentValue[m][0])
									.toString();
							sp[m] = (SpannableStringBuilder) Html
									.fromHtml(recentStr[m]);
						}
					}
					mValue1TextView.setText(sp[0].toString());
					mValue2TextView.setText(sp[1].toString());
					mValue3TextView.setText(sp[2].toString());
					mViewGroup.removeAllViews();
					for (int i = 0; i < mHealthChartListBean.healthChartBeans
							.size(); i++) {
						ImageView imageView = new ImageView(
								HealthChartActivity.this);
						LayoutParams lp = new LayoutParams(
								LayoutParams.WRAP_CONTENT,
								LayoutParams.WRAP_CONTENT);
						lp.setMargins(0, 0, 8, 0);
						imageView.setLayoutParams(lp);
						mImageViews[i] = imageView;
						if (i == 0) {
							mImageViews[i]
									.setBackgroundResource(R.drawable.scroll_indicator_selected);
						} else {
							mImageViews[i]
									.setBackgroundResource(R.drawable.scroll_indicator_normal);
						}
						mViewGroup.addView(mImageViews[i]);
					}
					mGuidePageAdapter.notifyDataSetChanged();
				} else {
					if (SystemTool.checkNet(HealthChartActivity.this)) {
						ViewInject.toast(getString(R.string.net_error));
					} else {
						ViewInject.toast(getString(R.string.query_data_error));
					}
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				KJLoger.debug(t.toString());
				if (SystemTool.checkNet(HealthChartActivity.this)) {
					ViewInject.toast(getString(R.string.query_data_error));
				} else {
					ViewInject.toast(getString(R.string.net_error));
				}
			}

			@Override
			public void onFinish() {
				super.onFinish();
				dialog.dismiss();
			}
		},HealthChartActivity.this);
	}

	@Override
	public void initData() {
		super.initData();

		String username = PreferenceUtil.readString(this,
				Contants.SP.username);
		TextViewUtil textViewUtil = new TextViewUtil();
		String info = String.format(getString(R.string.welcome_info),
				username);
		int start = info.indexOf(username);
		int end = start + username.length();
		tvInfo.setText(textViewUtil.getForegroundColorSpan(
				this, info, start, end,
				"#e95013"));

		mGuidePageAdapter = new GuidePageAdapter(this);
		mViewPager.setAdapter(mGuidePageAdapter);
		mViewPager.setOnPageChangeListener(this);

		// 0(���10��) 1�����1�£� 3�����3���£�' -1(��ѡʱ���)
		String beginTime = String.valueOf(System.currentTimeMillis()
				- (long) 90 * 24 * 3600 * 1000);
		String timetype = "0";
		queryData(timetype, beginTime,
				String.valueOf(System.currentTimeMillis()));
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (null != mLinearLayout) {
			mLinearLayout.removeAllViews();
		}
		if (null != mHealthChartListBean
				&& null != mHealthChartListBean.healthChartBeans) {
			mHealthChartListBean.healthChartBeans.clear();
			mHealthChartListBean.healthChartBeans = null;
		}
		mHealthChartListBean = null;
		if (null != mGuidePageAdapter) {
			mGuidePageAdapter.clear();
		}
	}

	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {

	}

	@Override
	public void onPageSelected(int position) {
		String recentStr[] = new String[3];
		HealthChartBean healthChartBean = mHealthChartListBean.healthChartBeans
				.get(position);
		String recentTitleStr[] = healthChartBean.recentTitle;
		String recentValue[][] = healthChartBean.recentValue;
		SpannableStringBuilder sp[] = new SpannableStringBuilder[3];
		for (int m = 0; m < recentTitleStr.length; m++) {
			if (m < 3 && null != recentValue[m][0]) {
				recentStr[m] = new StringBuffer(recentTitleStr[m]).append(" ")
						.append(recentValue[m][0]).toString();
				sp[m] = (SpannableStringBuilder) Html.fromHtml(recentStr[m]);
			}
		}
		mValue1TextView.setText(sp[0].toString());
		mValue2TextView.setText(sp[1].toString());
		mValue3TextView.setText(sp[2].toString());
		/*
		 * mTitleTextView.setText(mHealthChartListBean.healthChartBeans
		 * .get(position).title);
		 */
		for (int i = 0; i < mImageViews.length; i++) {
			mImageViews[position]
					.setBackgroundResource(R.drawable.scroll_indicator_selected);
			if (position != i) {
				mImageViews[i]
						.setBackgroundResource(R.drawable.scroll_indicator_normal);
			}
		}
	}

	@Override
	public void onPageScrollStateChanged(int state) {
	}

	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		Contants.starTime = System.currentTimeMillis();
		switch (v.getId()) {
		case R.id.btn_1:
			mViewPager.setCurrentItem(0);
			break;
		case R.id.btn_2:
			mViewPager.setCurrentItem(1);
			break;
		case R.id.btn_3:
			mViewPager.setCurrentItem(2);
			break;
		case R.id.btn_select:
			SelectDialog dialog = new SelectDialog(this,
					new DialogInterfaceListener() {

						@Override
						public void itemClick(View view) {
							String begintime = "";
							String timetype = view.getTag().toString();
							if (timetype.equals("0")) {
								begintime = String.valueOf(System
										.currentTimeMillis()
										- (long) 90
										* 24
										* 3600 * 1000);
								queryData(timetype, begintime, String
										.valueOf(System.currentTimeMillis()));
								// tvDate.setText(R.string.time_1);
							} else if (timetype.equals("1")) {
								begintime = String.valueOf(System
										.currentTimeMillis()
										- (long) 30
										* 24
										* 3600 * 1000);
								queryData(timetype, begintime, String
										.valueOf(System.currentTimeMillis()));
								// tvDate.setText(R.string.time_2);
							} else if (timetype.equals("3")) {
								begintime = String.valueOf(System
										.currentTimeMillis()
										- (long) 90
										* 24
										* 3600 * 1000);
								queryData(timetype, begintime, String
										.valueOf(System.currentTimeMillis()));
								// tvDate.setText(R.string.time_3);
							} else {
								// tvDate.setText(R.string.time_4);
								Calendar calendar = Calendar.getInstance();
								DoubleDatePickerDialog dialog = new DoubleDatePickerDialog(
										HealthChartActivity.this, calendar
												.get(Calendar.YEAR), calendar
												.get(Calendar.MONTH), calendar
												.get(Calendar.DAY_OF_MONTH),
										calendar.get(Calendar.YEAR), calendar
												.get(Calendar.MONTH), calendar
												.get(Calendar.DAY_OF_MONTH));
								dialog.setOnDateSetListener(onDateSetListener);
								dialog.show();
							}
						}
					});
			dialog.show();
			break;
		case R.id.btn_back:
			finish();
			break;
		}
	}

	private OnDateSetListener onDateSetListener = new OnDateSetListener() {

		@Override
		public void onDateSet(int start_year, int start_monthOfYear,
				int start_dayOfMonth, int end_year, int end_monthOfYear,
				int end_dayOfMonth) {
			Calendar startCalendar = Calendar.getInstance();
			startCalendar.set(start_year, start_monthOfYear, start_dayOfMonth,
					0, 0, 0);

			Calendar endCalendar = Calendar.getInstance();
			endCalendar.set(end_year, end_monthOfYear, end_dayOfMonth, 23, 59,
					59);

			String beginTime = String.valueOf(startCalendar.getTimeInMillis());
			String endTime = String.valueOf(endCalendar.getTimeInMillis());
			queryData("-1", beginTime, endTime);
		}
	};

}
